package com.ssyc.student.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.TypeTextView;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.student.R;
import com.ssyc.student.bean.StateInfo;
import com.ssyc.student.util.PetUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--编辑宠物姓名
 * Created by Administrator on 2018/4/19 0019.
 */

public class StudentEditPetNameActivity extends BaseActivity implements View.OnClickListener {

    //输入框
    private EditText etName;
    //监控输入框的输入个数
    private TextView tvNum;
    private Button btOK;
    private LinearLayout llMain;

    //打字机TextView
    private TypeTextView tvChoosePet;
    //显示宠物图像的ImageView
    private ImageView lvPet;

    //用于控制打字机是否打印完毕的标记
    private boolean isPrintFinished;

    //四种宠物类型的集合
    private int[] pets = {R.drawable.student_flicker_dog, R.drawable.student_flicker_cat,
            R.drawable.student_flicker_monster, R.drawable.student_flicker_panda};
    //返回按钮
//    private ImageView iv_back;

    public static String PETFINISH = "StudentPetFinish";

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_edit_pet_name;
    }

    @Override
    protected void init() {

        showContent();
        //初始化视图
        initView();
        //设置监听
        initListener();
    }


    /**
     * 初始化控件
     */
    public void initView() {

//        iv_back = findViewById(R.id.iv_back);
//        iv_back.setOnClickListener(this);

        etName = findViewById(R.id.et_name);
        tvNum = findViewById(R.id.tv_num);
        btOK = findViewById(R.id.bt_OK);
        btOK.setOnClickListener(this);
        llMain = findViewById(R.id.ll_main);
        tvChoosePet = findViewById(R.id.tv_choose_pet);
        tvChoosePet.start(getResources().getString(R.string.st_pet_edit_name));

        tvChoosePet.setOnTypeViewListener(new TypeTextView.OnTypeViewListener() {
            @Override
            public void onTypeStart() {

            }

            @Override
            public void onTypeOver() {
                isPrintFinished = true;
                //文字显示完成后,如果还没有输入宠物名称,则按钮继续保持灰色不可点击,否则高亮按钮并且可以点击
                String content = etName.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    btOK.setBackgroundResource(R.drawable.student_bt_ok_unselect);
                    btOK.setEnabled(false);
                } else {
                    btOK.setBackgroundResource(R.drawable.student_bt_ok_select);
                    btOK.setEnabled(true);
                }
            }
        });

        lvPet = findViewById(R.id.lv_pet);
        lvPet.setImageResource(pets[SPUtil.getInt(this, SpKeys.PETTYPE) - 1]);
    }

    /**
     * 设置输入名称EditText的监听
     */
    private void initListener() {
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String content = etName.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    tvNum.setText("0/10");
                    btOK.setBackgroundResource(R.drawable.student_bt_ok_unselect);
                    btOK.setEnabled(false);
                } else {
                    if (isPrintFinished) {
                        btOK.setBackgroundResource(R.drawable.student_bt_ok_select);
                        btOK.setEnabled(true);
                    } else {
                        btOK.setBackgroundResource(R.drawable.student_bt_ok_unselect);
                        btOK.setEnabled(false);
                    }
                    if (content.length() > 10) {
                        tvNum.setText("10/10");
                        SnackbarUtil.ShortSnackbar(llMain, "最多只能输入10个字", 0).show();
                    } else {
                        tvNum.setText(content.length() + "/10");
                    }
                }
            }
        });
    }

    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.bt_OK) {
            //确定按钮
            String name = etName.getText().toString().trim();
            if (TextUtils.isEmpty(name)) {
                SnackbarUtil.ShortSnackbar(llMain, "您还没有给宠物取名字哦", 0).show();
                return;
            }

            //宠物名字正则
//            if (!isRegCheck(name)) {
//                SnackbarUtil.ShortSnackbar(llMain, "宠物名字只能使用中文和英文", 0).show();
//                return;
//            }

            //用于Sp保存宠物名字,并进行界面跳转
                SPUtil.put(this, SpKeys.PETNAME, name);

                // 请求服务器,上传领取的宠物的相关信息
                doGetPetHttp();

        }
    }

    /**
     * 宠物姓名正则
     */
    private boolean isRegCheck(String str) {

        return str.matches("^[a-zA-Z0-9\\u4e00-\\u9fa5]+$");
    }


    /**
     * 请求服务器上传领取宠物的相关信息
     */
    private void doGetPetHttp() {

        String acc = SPUtil.getString(this, SpKeys.ACCOUNT);
        String token = SPUtil.getString(this, SpKeys.TOKEN1);

        CustomDialogManager.show(this, "上传中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("acc", acc);
        map.put("role", "0");
        map.put("apptoken", token);
        map.put("pettype", PetUtils.getPetType());
        map.put("petsex", PetUtils.getPetSex());
        map.put("petname", PetUtils.getPetName());
        HttpUtils.post(HttpAdress.GETPET, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                //请求失败
                CustomDialogManager.dissmiss();
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                //请求成功
                Log.i("test", response);
                StateInfo info = GsonUtil.jsonToBean(response, StateInfo.class);
                if (info != null) {
                    if ("200".equals(info.getState())) {

                        SPUtil.put(StudentEditPetNameActivity.this, SpKeys.SERVICEPETTYPE, PetUtils.getPetType());

                        Intent intent = new Intent(StudentEditPetNameActivity.this, StudentGetpetLastActivity.class);
                        startActivity(intent);
                        //通知首页关闭
                        EventBus.getDefault().post(new BusInfo(PETFINISH));
                        finish();
                    } else {
                        UiUtils.Toast("错误码是:" + info.getState(), false);
                    }
                }
            }
        });
    }

    /**
     * 生命周期释放
     */
    @Override
    protected void onDestroy() {
        if (null != tvChoosePet) {
            tvChoosePet.stop();
        }
        super.onDestroy();
    }
}
